package com.aaa.controller.api;

import com.aaa.entity.User;
import com.aaa.vo.Result;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("system/api/user")
public class UploadControllerDev {

    @PostMapping("alyFile")
    public Result<String> upload03(MultipartFile file){
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5t84quSBpcWa7h94zJS6";
        String accessKeySecret = "5XZcAsYlO7mxhlVj9adgMQYlchGQgc";
        // 填写Bucket名称
        String bucketName = "gjl0404";

        //获取源文件的昵称 //获取文件后缀的位置 //截取后缀
        String oldName = file.getOriginalFilename();
        int i = oldName.lastIndexOf(".");
        String substring = oldName.substring(i);
        String UUname = UUID.randomUUID().toString();
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String objectName = UUname+substring;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            String content = "Hello OSS";
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file.getInputStream());
            // 上传字符串。
            ossClient.putObject(putObjectRequest);
//            https://gjl0404.oss-cn-beijing.aliyuncs.com/0654fd36-5b26-4998-b371-5f7e48313690.png
        }catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        String picpath="https://"+bucketName+"."+endpoint+"/"+objectName;



        return new Result<>(2000,"成功",picpath);
    }

}
